#include <iostream>
#include "camserver.h"
#include "camthread.h"

using namespace std;

CameraServer::CameraServer(int port)
: Server(port)
, capture(0) {
	this->capture = cvCreateCameraCapture(0);
	if (!this->capture) {  
		printf("Camera initialization failed\n");
	}
}

CameraServer::~CameraServer() {
	wxCriticalSectionLocker enter(this->protectFrameCS);
	if (this->readThread) {
		if (this->readThread->Delete() != wxTHREAD_NO_ERROR) {
			printf("Can\'t stop read thread");
		}
		this->readThread = 0;
	}
	if (this->capture != 0) {
		cvReleaseCapture(&(this->capture));
	}
}

void CameraServer::end() {
	wxCriticalSectionLocker enter(this->protectFrameCS);
	Server::end();
}

ClientServerThread * CameraServer::createClientServerThread(SocketClient * client) {
	return new CameraThread();
}

void CameraServer::afterClientAccept(SocketClient * client) {
	printf("connect: %s\n", client->getIpAddress());
}

bool CameraServer::start() {
	bool res = this->startCameraReadThread();
	if (!res) return false;
	return Server::start();
}

bool CameraServer::startCameraReadThread() {
	wxCriticalSectionLocker open(this->protectFrameCS);
	this->readThread = new ReadThread(this);
	if (this->readThread->Create() != wxTHREAD_NO_ERROR) {
		return false;
	}
	this->readThread->Run();
	return true;
}

void CameraServer::setCurrentFrame(IplImage * frame) {
	this->curFrame = frame;
	this->mat = cvEncodeImage(".jpg", this->curFrame);
}

IplImage * CameraServer::getCurrentFrame() const {
	return this->curFrame;
}

CvCapture * CameraServer::getCapture() const {
	return this->capture;
}
